package cn.liu.study.db.configurer;

import cn.liu.study.db.core.Result;
import cn.liu.study.db.core.ResultCode;
import cn.liu.study.db.core.ServiceException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.config.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * Spring MVC 配置
 */
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
    private final Logger LOGGER = LoggerFactory.getLogger(WebMvcConfigurer.class);

    @Value("${swagger.enabled:true}")
    private Boolean swaggerEnable;

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //使用阿里 FastJson 作为JSON MessageConverter
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        //保留空的字段
        config.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
        config.setSerializerFeatures(SerializerFeature.WriteNullStringAsEmpty);
        // 按需配置，更多参考FastJson文档哈

        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
        converters.add(converter);
    }


    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
        //统一异常处理
        exceptionResolvers.add((request, response, handler, e) -> {
            Result result = new Result();
            if (e instanceof ServiceException) {
                result.setCode(ResultCode.FAIL).setMessage(e.getMessage());
                LOGGER.info(e.getMessage());
            } else if (e instanceof NoHandlerFoundException) {
                result.setCode(ResultCode.NOT_FOUND).setMessage("接口 [" + request.getRequestURI() + "] 不存在");
            } else if (e instanceof MethodArgumentNotValidException) {
                //bean校验异常
                StringBuffer errorMsg = new StringBuffer();
                MethodArgumentNotValidException c = (MethodArgumentNotValidException) e;
                List<ObjectError> errors = c.getBindingResult().getAllErrors();
                for (ObjectError error : errors) {
                    errorMsg.append(error.getDefaultMessage()).append(";");
                }
                result.setCode(ResultCode.FAIL).setMessage("接口 [" + request.getRequestURI() + "] 请求不规范");
                result.setData(errorMsg);
            } else if (e instanceof ConstraintViolationException) {
                //单参数校验异常
                StringBuffer errorMsg = new StringBuffer();
                Set<ConstraintViolation<?>> errors = ((ConstraintViolationException) e).getConstraintViolations();
                for (ConstraintViolation error : errors) {
                    errorMsg.append(error.getMessage()).append(";");
                }
                result.setCode(ResultCode.FAIL).setMessage("接口 [" + request.getRequestURI() + "] 请求不规范");
                result.setData(errorMsg);
            } else {
                if (e instanceof MissingServletRequestParameterException || e instanceof HttpMessageNotReadableException) {
                    result.setCode(ResultCode.FAIL).setMessage("接口 [" + request.getRequestURI() + "] 请求不规范");
                } else {
                    result.setCode(ResultCode.INTERNAL_SERVER_ERROR).setMessage("接口 [" + request.getRequestURI() + "] 内部错误，请联系管理员");
                }
                String message;
                if (handler instanceof HandlerMethod) {
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    message = String.format("接口 [%s] 出现异常，方法：%s.%s，异常摘要：%s",
                            request.getRequestURI(),
                            handlerMethod.getBean().getClass().getName(),
                            handlerMethod.getMethod().getName(),
                            e.getMessage());
                } else {
                    message = e.getMessage();
                }
                result.setData(message);
                LOGGER.error(message, e);
            }
            responseResult(response, result);
            return new ModelAndView();
        });
    }


    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //解决跨域问题
        //registry.addMapping("/**");
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //添加拦截器
//        registry.addInterceptor(new HandlerInterceptorAdapter() {
//            @Override
//            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//                return true;
//
//            }
//        });
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        if (swaggerEnable) {
            registry.addRedirectViewController("/v2/api-docs", "/v2/api-docs?group=restful-api");
            registry.addRedirectViewController("/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui");
            registry.addRedirectViewController("/swagger-resources/configuration/security", "/swagger-resources/configuration/security");
            registry.addRedirectViewController("/swagger-resources", "/swagger-resources");
        }
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (swaggerEnable) {
            registry.addResourceHandler("/swagger-ui.html**").addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    }

    private void responseResult(HttpServletResponse response, Result result) {
        try {
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            response.setStatus(200);
            response.getWriter().write(JSON.toJSONString(result));
        } catch (IOException ex) {
            LOGGER.error(ex.getMessage());
        }
    }

}
